import ajax from '@U/ajax'

export default {
  menuCache:null,
  authCache:null,
  _isRun:false,
  run(){
    if(this._isRun){
      return;
    }
    this._isRun = true;
    setInterval(()=>{
      if(!this.authCache) return;
      var doms = document.querySelectorAll("[xy-auth-code]");
      if(!doms || doms.length == 0) return;
      doms.forEach(dom => {
        var code = dom.getAttribute("xy-auth-code");
        if(!code) return;
        if(this.authCache.indexOf(code) != -1){
          dom.className = dom.className.replace("is-disabled","");
          dom.removeAttribute("xy-auth-code");
          dom.removeAttribute("disabled");
          dom.setAttribute("title",dom.getAttribute("auth-title") || '')
          dom.removeAttribute("auth-title");
        }
      });
    },100);
  },
  listMenu(selector,success){
    
    var self = this;
    this.run();
    if(typeof selector == 'function'){
      success = selector;
      selector = null;
    }
    
    if(this.menuCache){
      success && success(this.menuCache);
      return;
    }
    
    var config = {};
    
    if(selector){
      config =  {
        loading: true,
        target: document.querySelector(selector),
        refresh:self.listMenu.bind(self,selector,success)
      };
    }
    ajax.postStream('/admin/auth/instance/authMenu/listUserMenu.do',{
      data:{},
      config:config,
      success(res){
        self.menuCache = res.object.menus || [];
        self.authCache = res.object.auth;
        success && success(self.menuCache);
      }
    });
  },
  delete(){
    this.menuCache = null;
  }
}